package com.sdp.th.controller;


import java.security.NoSuchAlgorithmException;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.sdp.core.bizc.db.Query;
import com.sdp.core.bizc.utils.UniqueCheckTools;
import com.sdp.core.bizc.vo.DataCenter;
import com.sdp.core.bizc.vo.Result;
import com.sdp.right.entity.SysEmp;
import com.sdp.right.service.RightExtService;
import com.sdp.th.db.th_emp.service.IThEmpService;
import com.sdp.th.entity.ThEmp;

/**
 * <p>
 * 人员信息 前端控制器
 * </p>
 *
 * @author zsp
 * @since 2025-04-12
 */
@RestController
@RequestMapping("/ThEmpController")
public class ThEmpController {

	@Autowired
	private IThEmpService iThEmpService;

	@Autowired
	private Query query;
	
	@Autowired
	private UniqueCheckTools uniqueCheckTools;
	
	@Autowired
	private RightExtService rightExtService;
	
	
	@PostMapping(value = "/page")
	public Result<?> page(@RequestBody DataCenter dataCenter) {
		return Result.ok(query.page(iThEmpService, ThEmp.class, dataCenter));
	}
	
	
	@PostMapping(value = "/save")
	@Transactional(rollbackFor=Exception.class)
	public Result<?> save(@RequestBody ThEmp emp) throws NoSuchAlgorithmException {
		if(emp==null) {
			return Result.error("人员信息为空");
		}
		
		SysEmp sysEmp = new SysEmp();
		BeanUtils.copyProperties(emp, sysEmp);
		
		
		if(StringUtils.isEmpty(emp.getKeyId())) {
			Result<?> r = uniqueCheckTools.isUniqueSingle(iThEmpService, ThEmp.class, new String[] {"empNo","accountNo"}, "keyId", emp, null, false);
			if(r==null || !r.isSuccess()) {
				return Result.error("人员工号和账号不能重复");
			}

			iThEmpService.save(emp);
			
			//向账号表中添加人员
			rightExtService.addSysEmp(sysEmp);
			
		}else {
			Result<?> r = uniqueCheckTools.isUniqueSingle(iThEmpService, ThEmp.class, new String[] {"empNo","accountNo"}, "keyId", null, emp, false);
			if(r==null || !r.isSuccess()) {
				return Result.error("人员工号和账号不能重复");
			}

			iThEmpService.updateById(emp);
			
			//更新账号表中人员信息
			sysEmp.setKeyId(null);
			rightExtService.updateSysEmpByAccountNo(emp.getAccountNo(), sysEmp);
		}

		return Result.ok();
	}
}

